package com.axujie.tlgypt.service.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author XuJie
 * @Date 2016年7月30日 描述：构建树形的数据结构
 * 
 *       方式一：一次查询出所有的数据，然后进行树形数据的构造 方式二：迭代查询数据库数据
 * 
 *       方式一较方式二快
 */
public class TreeHelper {

	/**
	 * 构建树形数据源
	 * 
	 * @param srcList
	 *            原始数据集合
	 * @param fidName
	 *            父级字段的名称（记录上级字段的字段名）
	 * @return 构造好的树形数据List集合
	 */
	public static List<Map<String, Object>> buildTree(
			List<Map<String, Object>> srcList, String fidName, String idName) {
		List<Map<String, Object>> descList = DeepCloneUtils
				.clone((ArrayList<Map<String, Object>>) srcList);// 进行深度拷贝
		for (Map<String, Object> srcMap : srcList) {
			if (srcMap.get(fidName) != null) {
				String fid = srcMap.get(fidName).toString();
				Map<String, Object> fMap = findParent(descList, fid, idName);
				if (fMap != null) {// 父ID是否在集合中存在
					if (fMap.get("children") != null) {
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> childrenList = (List<Map<String, Object>>) fMap
								.get("children");
						// childrenList.add(srcMap);//将集合添加到父级集合的child中
						childrenList.add(findById(descList, srcMap.get(idName)
								.toString(), idName));
					} else {
						List<Map<String, Object>> childrenList = new ArrayList<Map<String, Object>>();
						// childrenList.add(srcMap);
						childrenList.add(findById(descList, srcMap.get(idName)
								.toString(), idName));
						fMap.put("children", childrenList);
						fMap.put("state", "closed");// 若有子节点，则将其关闭
					}
					descList.remove(findById(descList, srcMap.get(idName)
							.toString(), idName));// 将集合从目标中移除
				}
			}
		}
		return descList;
	}

	/**
	 * 查找是否在List集合中存在
	 * 
	 * @param list
	 * @param id
	 * @return 指定ID的map集合
	 */
	private static Map<String, Object> findParent(
			List<Map<String, Object>> list, String id, String idName) {
		for (Map<String, Object> map : list) {
			if (map.get(idName).toString().trim().equals(id)) {// 应该先把一级的查询完，再去深入迭代
				return map;
			}
		}
		for (Map<String, Object> map : list) {
			if (map.get("children") != null) {
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> childrenList = (List<Map<String, Object>>) map
						.get("children");
				if (findParent(childrenList, id, idName) != null) {
					return findParent(childrenList, id, idName);
				}
			}
		}
		return null;
	}

	/**
	 * 在list中查找指定ID的集合
	 * 
	 * @param list
	 * @param id
	 * @return
	 */
	private static Map<String, Object> findById(List<Map<String, Object>> list,
			String id, String idName) {
		for (Map<String, Object> map : list) {
			if (map.get(idName).toString().trim().equals(id)) {
				return map;
			}
		}
		return null;
	}
}
